package com.xkdx.guangguang.fragment.brand;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.adapter.BrandCommentAdapter;
import com.xkdx.guangguang.adapter.NewsInfoAdapter;
import com.xkdx.guangguang.adapter.ShopAdapter;
import com.xkdx.guangguang.card.CardInfoFragment;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.brand.BrandInfoModule.BrandInfo;
import com.xkdx.guangguang.fragment.brand.branch.BranchFragment;
import com.xkdx.guangguang.fragment.brand.photo.BrandPhotoAlbumFragment;
import com.xkdx.guangguang.fragment.newsinfo.DiscountFragment;
import com.xkdx.guangguang.fragment.newsinfo.NewsFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.presistence.attention.AttentionBrandAction;
import com.xkdx.guangguang.presistence.attention.AttentionBrandModule;
import com.xkdx.guangguang.presistence.attention.AttentionBrandPresistence;
import com.xkdx.guangguang.shareclass.BrandCommentaryResult;
import com.xkdx.guangguang.shareclass.BrandDetail;
import com.xkdx.guangguang.shareclass.DiscountInfo;
import com.xkdx.guangguang.shareclass.Shop;
import com.xkdx.guangguang.util.SharePrefenceUtil;
import com.xkdx.guangguang.wiget.XListView;
import com.xkdx.guangguang.wiget.XListView.IXListViewListener;

public class BrandInfoFragment extends BaseFragment implements OnClickListener,
		IXListViewListener {
	View view;
	public static Map<String, Integer> attentionBrand = new HashMap<String, Integer>();
	LayoutInflater inflater;
	TextView tab1;
	TextView tab2;
	TextView tab3;
	TextView tab4;
	TextView brandName, attention, noPartInfo;
	TextView introduce;
	String cityID;
	String brandID;
	Button back;
	LinearLayout attention_ll;
	View card_link_view;
	ImageView card_link;
	String UserID, LoginToken;
	View view_newProduct, view_brandIntroduce, view_childShopInfo,
			view_brand_commentary;
	ListView partShoplistView; // 分店信息
	List<Shop> list;// 分店信息
	XListView newProductBrandListView;// 新品信息
	BrandDetail brandDetail;
	int attentCount;
	RelativeLayout container;
	ImageView focuse_im;
	ImageView newsTip;
	BrandInfoAction brandInfoAction;
	BrandInfoModule brandInfoModule;
	BrandInfoPresistence brandInfoPresistence;

	BrandCommentaryResult brandCommentary;
	List<Shop> partShopList;
	BrandInfo brandInfo;
	List<DiscountInfo> newsInfoList;

	NewsInfoAdapter newsAdapter;
	boolean isLoadMore = false;
	int PageIndex = 1;

	ListView brandCommentListView;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options, focuse_options;

	AttentionBrandAction attentionBrandAction;
	AttentionBrandModule attentionBrandModule;
	AttentionBrandPresistence attentionBrandPresistence;

	// 新品信息加载更多
	BrandInfoNewAction brandInfoNewAction;
	BrandInfoNewsModule brandInfoNewsModule;
	BrandInfoNewsPresistence brandInfoNewsPresistence;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		cityID = new SharePrefenceUtil(getActivity(), IConstants.SP_CITY)
				.getCityID();
		brandID = getArguments().getString("brandID");
		inflater = LayoutInflater.from(getActivity());

		SharePrefenceUtil su_user = new SharePrefenceUtil(getActivity(),
				IConstants.SP_USER);
		UserID = su_user.getUserID();
		LoginToken = su_user.getUserLoginToken();
		focuse_options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.focus_image)
				.showImageForEmptyUri(R.drawable.focus_image)
				.showImageOnFail(R.drawable.focus_image)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.shop_empty)
				.showImageForEmptyUri(R.drawable.shop_empty)
				.showImageOnFail(R.drawable.shop_empty)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.brand_info, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		IConstants.hideInputMethodAways(getActivity(), view);
		// 品牌新品优惠信息
		view_newProduct = inflater.inflate(R.layout.shop_detail_newsinfo, null);
		newProductBrandListView = (XListView) view_newProduct
				.findViewById(R.id.shop_detail_newslistview);
		newProductBrandListView.setPullRefreshEnable(false);
		newProductBrandListView.setPullLoadEnable(true);
		newsTip = (ImageView) view_newProduct.findViewById(R.id.default_image);
		card_link_view = (View) view_newProduct.findViewById(R.id.ic_card_link);
		card_link = (ImageView) card_link_view.findViewById(R.id.card_link_im);

		// 品牌介紹
		view_brandIntroduce = inflater.inflate(R.layout.brandintroduce, null);
		introduce = (TextView) view_brandIntroduce
				.findViewById(R.id.brand_introduce);
		// 品牌分店信息
		view_childShopInfo = inflater.inflate(R.layout.brandchildshop, null);
		partShoplistView = (ListView) view_childShopInfo
				.findViewById(R.id.strollBrand_part_list);
		noPartInfo = (TextView) view_childShopInfo
				.findViewById(R.id.no_part_shop);
		// 2013-4-25 add
		// 品牌评论
		view_brand_commentary = inflater.inflate(R.layout.shop_detail_comment,
				null);
		brandCommentListView = (ListView) view_brand_commentary
				.findViewById(R.id.shop_detail_shopcomment_listview);

		container = (RelativeLayout) view.findViewById(R.id.container);
		attention_ll = (LinearLayout) view.findViewById(R.id.attention);
		brandName = (TextView) view.findViewById(R.id.shop_title);
		attention = (TextView) view.findViewById(R.id.number);
		back = (Button) view.findViewById(R.id.back_stroll_brand_part);
		focuse_im = (ImageView) view.findViewById(R.id.adverse);

		tab1 = (TextView) view.findViewById(R.id.tab1);
		tab2 = (TextView) view.findViewById(R.id.tab2);
		tab3 = (TextView) view.findViewById(R.id.tab3);
		tab4 = (TextView) view.findViewById(R.id.tab4);

		brandInfoAction = new BrandInfoAction(brandID, cityID);
		brandInfoModule = new BrandInfoModule();

	}

	@Override
	public void setOnClick() {
		tab1.setOnClickListener(this);
		tab2.setOnClickListener(this);
		tab3.setOnClickListener(this);
		tab4.setOnClickListener(this);
		attention_ll.setOnClickListener(this);
		back.setOnClickListener(this);
		focuse_im.setOnClickListener(this);
		card_link.setOnClickListener(this);
	}

	@Override
	public void showLoading() {
		dataLoadDialog.show();
		brandInfoPresistence = new BrandInfoPresistence(this);
		if (IConstants.isCommitSuccess) {
			brandInfoPresistence.mUseCache = false;
		} else {
			brandInfoPresistence.mUseCache = true;
		}
		((ManagerActivity) getActivity()).addCurrentTask(brandInfoPresistence);
		brandInfoPresistence.setActitons(brandInfoAction);
		brandInfoPresistence.setModule(brandInfoModule);
		brandInfoPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (brandInfoPresistence != null) {
					brandInfoPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			brandInfo = brandInfoModule.brandInfo;
			newsInfoList = brandInfoModule.newsInfoList;
			partShopList = brandInfoModule.partShopList;
			brandCommentary = brandInfoModule.brandCommentary;
			IConstants.Brand_CommentNum = brandCommentary.getDataCount();
			setBrandInfo();
			setNewsInfo();
			setPartShop();
			setBrandCommentary();
			container.removeAllViews();
			container.addView(view_newProduct);
		} else {
			refresh(map);
		}

	}

	private void setBrandCommentary() {
		BrandCommentAdapter aAdapter = new BrandCommentAdapter(this,
				brandCommentary.getBrandCommentList(), imageLoader, brandID,
				brandDetail.getBrandName());
		brandCommentListView.setAdapter(aAdapter);

	}

	/*
	 * 分店信息
	 */
	private void setPartShop() {
		if (partShopList.size() != 0) {
			ShopAdapter adapter = new ShopAdapter(getActivity(), partShopList,
					imageLoader);
			partShoplistView.setAdapter(adapter);
			partShoplistView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					BranchFragment branchFragment = new BranchFragment();
					Bundle b = new Bundle();
					b.putString("shopID", partShopList.get(position)
							.getShopID());
					Log.i("shopID", partShopList.get(position).getShopID());
					branchFragment.setArguments(b);
					getFragmentManager().beginTransaction()
							.replace(R.id.fragment, branchFragment)
							.addToBackStack(null).commit();

				}
			});
		} else {
			noPartInfo.setVisibility(View.VISIBLE);
		}
	}

	/*
	 * 新品优惠
	 */
	private void setNewsInfo() {
		if (newsInfoList.size() != 0) {
			card_link_view.setVisibility(View.GONE);
			newsAdapter = new NewsInfoAdapter(getActivity(), newsInfoList,
					imageLoader);
			View view = LayoutInflater.from(getActivity()).inflate(
					R.layout.card_info_link_im, null);
			ImageView im = (ImageView) view.findViewById(R.id.card_link_im);
			im.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					CardInfoFragment cardInfoFragment = new CardInfoFragment();
					Bundle b = new Bundle();
					b.putString(CardInfoFragment.CON1, "brand");
					b.putString(CardInfoFragment.CON1VALUE, brandID);
					cardInfoFragment.setArguments(b);
					getFragmentManager().beginTransaction()
							.replace(R.id.fragment, cardInfoFragment)
							.addToBackStack(null).commit();

				}
			});
			newProductBrandListView.addHeaderView(view);

			newProductBrandListView.setAdapter(newsAdapter);
			newProductBrandListView.setXListViewListener(this);
			newProductBrandListView
					.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							String infoType = newsInfoList.get(position - 2)
									.getInfoType();
							FragmentTransaction ft = getFragmentManager()
									.beginTransaction();
							if (infoType.equals("1")) {
								DiscountFragment discountFragment = new DiscountFragment();
								ft.replace(R.id.fragment, discountFragment);
								Bundle b = new Bundle();
								b.putString("infoID",
										newsInfoList.get(position - 2)
												.getInfoID());
								discountFragment.setArguments(b);
								ft.addToBackStack(null);
								ft.commit();
							} else {
								NewsFragment newsFragment = new NewsFragment();
								ft.replace(R.id.fragment, newsFragment);
								Bundle b = new Bundle();
								b.putString("infoID",
										newsInfoList.get(position - 2)
												.getInfoID());
								newsFragment.setArguments(b);
								ft.addToBackStack(null);
								ft.commit();
							}

						}
					});
		} else {
			card_link_view.setVisibility(View.VISIBLE);
			newsTip.setVisibility(View.VISIBLE);
		}

	}

	private void setBrandInfo() {
		setBrandDetail();
		introduce.setText(brandInfo.getIntro());
		brandName
				.setText(brandInfo.getBrandNameEn() + brandInfo.getBrandName());
		if (attentionBrand.containsKey(brandID)) {
			attention.setText(attentionBrand.get(brandID) + "");
		} else {
			attentCount = Integer.valueOf(brandInfo.getAttentionCount());
			attention.setText(attentCount + "");
		}
		if (brandInfo.getPictureList() != null
				&& brandInfo.getPictureList().size() != 0) {
			String foucse_im_url = IConstants.addSuffix(brandInfo
					.getPictureList().get(0), "_BigView");
			imageLoader.displayImage(foucse_im_url, focuse_im, focuse_options);
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		if (map.containsKey("0")) {
			if (attentionBrandModule.isAttentBrandSuccess) {
				attentionBrand.put(brandID, attentCount + 1);
				attention.setText(attentCount + 1 + "");
				Toast.makeText(getActivity(), "关注成功", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(getActivity(), "已关注", Toast.LENGTH_SHORT).show();
			}

		} else {
			showErrorTip(map);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tab1:
			container.removeAllViews();
			container.addView(view_newProduct);
			tab1.setBackgroundResource(R.drawable.shopinfo_subview_title_click);
			tab2.setBackgroundResource(0);
			tab3.setBackgroundResource(0);
			tab4.setBackgroundResource(0);
			break;
		case R.id.tab2:
			container.removeAllViews();
			container.addView(view_brand_commentary);
			tab2.setBackgroundResource(R.drawable.shopinfo_subview_title_click);
			tab1.setBackgroundResource(0);
			tab3.setBackgroundResource(0);
			tab4.setBackgroundResource(0);
			break;
		case R.id.tab3:
			container.removeAllViews();
			container.addView(view_childShopInfo);
			tab3.setBackgroundResource(R.drawable.shopinfo_subview_title_click);
			tab1.setBackgroundResource(0);
			tab2.setBackgroundResource(0);
			tab4.setBackgroundResource(0);
			break;
		case R.id.tab4:
			container.removeAllViews();
			container.addView(view_brandIntroduce);
			tab4.setBackgroundResource(R.drawable.shopinfo_subview_title_click);
			tab1.setBackgroundResource(0);
			tab2.setBackgroundResource(0);
			tab3.setBackgroundResource(0);
			break;
		case R.id.attention:
			SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			if (su.getUserLoginToken().equals("")) {
				UserLogin();
			} else {
				attentionBrandAction = new AttentionBrandAction(LoginToken,
						UserID, brandID);
				attentionBrandModule = new AttentionBrandModule();
				attentionBrandPresistence = new AttentionBrandPresistence(this);
				((ManagerActivity) getActivity())
						.addCurrentTask(attentionBrandPresistence);
				attentionBrandPresistence.setActitons(attentionBrandAction);
				attentionBrandPresistence.setModule(attentionBrandModule);
				attentionBrandPresistence.execute();
			}
			break;
		case R.id.back_stroll_brand_part:
			if (IConstants.isHasPush && !IConstants.isHasSelfPush) {
				IConstants.isHasPush = false;
				getActivity().finish();
			} else if (IConstants.isHasSelfPush) {
				// IConstants.isHasSelfPush = false;
				getActivity().finish();
			} else {
				getFragmentManager().popBackStack();
			}
			break;
		case R.id.adverse:
			IConstants.isFromInfo = true;
			BrandPhotoAlbumFragment photoAlbumFragment = new BrandPhotoAlbumFragment();
			Bundle bundle = new Bundle();
			bundle.putString("brandID", brandID);
			photoAlbumFragment.setArguments(bundle);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, photoAlbumFragment)
					.addToBackStack(null).commit();
			break;
		case R.id.card_link_im:
			CardInfoFragment cardInfoFragment = new CardInfoFragment();
			Bundle b = new Bundle();
			b.putString(CardInfoFragment.CON1, "brand");
			b.putString(CardInfoFragment.CON1VALUE, brandID);
			cardInfoFragment.setArguments(b);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, cardInfoFragment)
					.addToBackStack(null).commit();

			break;
		default:
			break;
		}

	}

	private void setBrandDetail() {
		if (brandDetail == null) {
			brandDetail = new BrandDetail();
		}
		if (brandInfo != null) {
			brandDetail.setBrandID(brandInfo.getBrandID());
			brandDetail.setBrandName(brandInfo.getBrandName());
			brandDetail.setBrandNameEn(brandInfo.getBrandNameEn());
			brandDetail.setLogo(brandInfo.getLogo());
			brandDetail.setBrandSimpleName(brandInfo.getBrandSimpleName());

		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLoadMore() {
		if (!isLoadMore) {
			isLoadMore = true;
			PageIndex++;
			brandInfoNewAction = new BrandInfoNewAction(brandID, cityID,
					String.valueOf(PageIndex));
			brandInfoNewsModule = new BrandInfoNewsModule();
			brandInfoNewsPresistence = new BrandInfoNewsPresistence(this);
			((ManagerActivity) getActivity())
					.addCurrentTask(brandInfoNewsPresistence);
			brandInfoNewsPresistence.setActitons(brandInfoNewAction);
			brandInfoNewsPresistence.setModule(brandInfoNewsModule);
			brandInfoNewsPresistence.execute();
		}

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		if (map.containsKey("0")) {
			if (brandInfoNewsModule.newsInfoList.size() != 0) {
				for (DiscountInfo discountInfo : brandInfoNewsModule.newsInfoList) {
					newsInfoList.add(discountInfo);
				}
				newsAdapter.notifyDataSetChanged();
			} else {
				if (getActivity() != null) {
					PageIndex--;
					Toast.makeText(getActivity(), "没有更多", Toast.LENGTH_SHORT)
							.show();
				}
			}
		} else {
			PageIndex--;
			showErrorTip(map);
		}

		newProductBrandListView.stopLoadMore();
		isLoadMore = false;
	}

}
